package test_package.linked;

public class Test1 {
    /**
     * 合并两条有序链表
     */
    private static final Node head1;
    static {
        head1 = new Node(1);
        head1.next = new Node(3);
        head1.next.next = new Node(5);
    }
    private static final Node head2;
    static {
        head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
    }
    public static void main(String[] args) {
        Node node = mergeNode(head1, head2);
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    public static Node mergeNode(Node head1, Node head2) {
        if (head1 == null || head2 == null) {
            return head1 == null ? head2 : head1;
        }
        Node newNode = new Node();
        Node temp = newNode;
        while (head1 != null && head2 != null) {
            if (head1.val < head2.val) {
                temp.next = head1;
                temp = temp.next;
                head1 = head1.next;
            } else {
                temp.next = head2;
                temp = temp.next;
                head2 = head2.next;
            }
        }
        if (head1 == null) {
            temp.next = head2;
        } else {
            temp.next = head1;
        }
        return newNode.next;
    }

}
class Node{
    public int val;
    public Node next;

    public Node() {
    }

    public Node(int val) {
        this.val = val;
    }
}
